//
//  FastJPush.swift
//  SmoSky
//
//  Created by zhuxietong on 2018/7/18.
//  Copyright © 2018年 tianrun. All rights reserved.
//

//注释以下代码即可


import Foundation
import UserNotifications
import soapp
import RxSwift
//import AdSupport

import UserNotifications



class BsNotice {
    var title = ""
    var body = ""
    var params:NSMutableDictionary = NSMutableDictionary()
    var uid = ""
    var isNew = false
}

var MessageChannalKey = "__channel__"

public enum CloudMsgType{
    case push
    case online
    var key:String{
        get{
            switch self {
            case .online:
                return "online"
            default:
                return "push"
            }
        }
    }

    static func ckeck(message:Any)-> CloudMsgType{
        if let msg = message as? NSMutableDictionary{

            if msg["aps.alert.title",""].len > 0
            {
                return .push
            }
        }
        else{
            return .online
        }
        return .online
    }
}

public typealias JPushObserver = (NSMutableDictionary,CloudMsgType) -> Void


extension FastJPush{
    

    
    
    
    private struct __AssociatedKeys {
        static var notify_key = "__easy_notify_key"
    }
    
    public var __notice: EasyNotification {
        get {
            if let obj = objc_getAssociatedObject(self, &__AssociatedKeys.notify_key) as? EasyNotification
            {
                return obj
            }
            let obj = EasyNotification()
            self.__notice = obj
            return obj
            
        }
        set {
            objc_setAssociatedObject(self, &__AssociatedKeys.notify_key, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}


public class FastJPush:NSObject,JPUSHRegisterDelegate{
    public func jpushNotificationAuthorization(_ status: JPAuthorizationStatus, withInfo info: [AnyHashable : Any]!) {
        
    }
    
    
    public static var observers = [JPushObserver]()
    public static let bag = DisposeBag()
    
    @available(iOS 10.0, *)
    public func jpushNotificationCenter(_ center: UNUserNotificationCenter!, openSettingsFor notification: UNNotification?) {
        
    }
    
    public static var isBindUser:Bool{
        get{
            return UserDefaults.standard.value(forKey: "JPUSH_isBindUser") as? Bool ?? false
        }
        set{
            UserDefaults.standard.set(newValue, forKey: "JPUSH_isBindUser")
        }
    }
    
    

    
    public static var registerID = ""


    public var receiveMessage:((NSMutableDictionary,CloudMsgType) -> Void) = {_,_ in }

    public static var net = JoTask().url("")

    public static func bind(registerID:String,checkTime:Int=3,finish:@escaping (Bool)->Void)
    {
        if checkTime > 1
        {
            if net.url_value.len < 1{
                fatalError("[FastJPush \(#line)] 极光推送需要设置registerID绑定方法")
            }
//            print("=====bindcheck")
            net.params(["regId":registerID]).log_response().log.json_handle { (status, msg, data, response,tsk) in
                if status.isSuccess{
                    FastJPush.isBindUser = true
                    finish(true)
                    return
                }
                FastJPush.bind(registerID: registerID, checkTime: (checkTime-1), finish: finish)
            }.run()
        }
        else{
            finish(false)
        }
    }
    
    public static var _share:FastJPush? = nil
    public static var share:FastJPush{
        get{
            guard let s = _share else{
                let _s = FastJPush()
                _share = _s
                return _s
            }
            return s
        }
    }
    public override init() {
        super.init()
        
        __notice.observer(JoUser.Notice.logout) { (ntype, notice) in
            FastJPush.isBindUser = false
        }
        
    }

    public func initSDK(option:[UIApplication.LaunchOptionsKey: Any]?) {
       
        UIApplication.rxActive.subscribe(onNext:{
            [weak self] f in
            self?.active = f

        }).disposed(by: FastJPush.bag)

//        if #available(iOS 10, *) {
//            let entity = JPUSHRegisterEntity()
//            entity.types = Int(UNAuthorizationOptions.alert.rawValue) |
//                Int(UNAuthorizationOptions.sound.rawValue) |
//                Int(UNAuthorizationOptions.badge.rawValue)
//            JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
//            
//        } else if #available(iOS 8, *) {
//            // 可以自定义 categories
//            JPUSHService.register(
//                forRemoteNotificationTypes: UIUserNotificationType.badge.rawValue |
//                    UIUserNotificationType.sound.rawValue |
//                    UIUserNotificationType.alert.rawValue,
//                categories: nil)
//        } else {
//            // ios 8 以前 categories 必须为nil
//            JPUSHService.register(
//                forRemoteNotificationTypes: UIRemoteNotificationType.badge.rawValue |
//                    UIRemoteNotificationType.sound.rawValue |
//                    UIRemoteNotificationType.alert.rawValue,
//                categories: nil)
//        }
//        
//        switch AppEnvironment.currentEnvironment {
//        case .dev:
//            JPUSHService.setup(withOption: option, appKey: SDKConfig.JPush.appKey, channel: "dev", apsForProduction: false)
//        default:
//            JPUSHService.setup(withOption: option, appKey: SDKConfig.JPush.appKey, channel: "App Store", apsForProduction: true)
//        }
//
//        JPUSHService.registrationIDCompletionHandler({ (IntID, StrID) in
//            print("____OOOOOD_____\(IntID)==|\(StrID)")
//            if let registID = StrID{
//                FastJPush.registerID = registID
//                print("success rigister JPush ReigisterID|\(IntID)==\(registID)")
//            }
//        })
        NotificationCenter.default.addObserver(self, selector: #selector(jpushDidSetup(notification:)), name: Notification.Name.jpfNetworkDidSetup, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(jpushDidRegist(notification:)), name: Notification.Name.jpfNetworkDidRegister, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(jpushDidLogin(notification:)), name: Notification.Name.jpfNetworkDidLogin, object: nil)

      
        if #available(iOS 10.0, *) {
            NotificationCenter.default.addObserver(self, selector: #selector(networkDidReceiveMessage(notification:)), name: Notification.Name.jpfNetworkDidReceiveMessage, object: nil)
        } else {
            // Fallback on earlier versions
        }

    }
    
    @objc func jpushDidLogin(notification:Notification){
        print("jpushDidLogin |\(notification)")
    }
    
    @objc func jpushDidRegist(notification:Notification){
        print("jpushDidRegist |\(notification)")
    }
    
    @objc func jpushDidSetup(notification:Notification){
        print("jpushDidSetup |\(notification)")
    }
    
    var active:UIApplication.Active = .didBecomeActive
    
    //在线消息
    @available(iOS 10.0, *)
    @objc func networkDidReceiveMessage(notification: Notification) {
        print("++dd++PPPP|\(notification)")
        switch active {
        case .didBecomeActive,.willEnterForeground:
            let userInfo = notification.userInfo?.mutable_dictionary ?? NSMutableDictionary()
            userInfo[MessageChannalKey] = CloudMsgType.online.key
//                    print("===== receive online message")
            DispatchQueue.main.async(execute: {
                let notify = UILocalNotification()
                notify.alertBody = userInfo["content",""]
                notify.alertTitle = userInfo["title",""]
                notify.soundName = "default"
                notify.userInfo =  notification.userInfo
                UIApplication.shared.presentLocalNotificationNow(notify)
            })
        default:
            break
        }
       
    }

    @available(iOS 10.0, *)
    public func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        let userInfo = notification.request.content.userInfo.mutable_dictionary
        let msg_type = CloudMsgType.ckeck(message: userInfo)//检查是在线消息还是推送
        let info = FastPushID.check(message: userInfo)//检查消息是否已经接收过
        
        print("uuiii0--\(userInfo)")
        
        if info.isExist
        {
            print("message is exist")
            completionHandler(Int(UNNotificationPresentationOptions().rawValue))
            return
        }
        else{
            
            for one in FastJPush.observers {
                one(userInfo,msg_type)
            }
           
//            FastJPush.share.receiveMessage(userInfo,msg_type)

            let msg = userInfo.any(nodes: "extras.msg","msg", default: NSMutableDictionary())
            let link = msg["link",""]
            if let _link = UIViewController.current as? LinkOnlineRefreshProtocol{
                if  _link.checkIfNeedRefresh(link: link){
                    _link.refreshLinkView()
                }
            }
            
//            AppLinkType.receive(message: userInfo)//收到消息的标记
            switch msg_type {
            case .online:
                print("收到在线消息:\n|\(userInfo)")
            default:
                print("收到推送消息:\n|\(userInfo)")
            }
        }
        
//        print("____||\(userInfo)==\(notification.request.content)")
        if notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(notification.request.content.userInfo)
        }
        // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
        completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue))
    }

    @available(iOS 10.0, *)
    public func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {

        let userInfo = response.notification.request.content.userInfo
        print("click message|\(userInfo.mutable_dictionary)")

        _ = FastPushID.check(message: userInfo.mutable_dictionary)//检查消息是否已经接收过；外部点击推送跳转会在该入口首先收到消息需要在此处也设置检查

        let msg = userInfo.mutable_dictionary.any(nodes: "extras.msg","msg", default: NSMutableDictionary())
        let link = msg["link",""]
        
        if let _link = UIViewController.current as? LinkOnlineRefreshProtocol{
            
            if  !_link.checkIfNeedRefresh(link: link){
                AppLink.open(link: link)
            }
        }
        
        if response.notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo)
        }
        // 系统要求执行这个方法
        completionHandler()
    }
}

class FastPushID{
    fileprivate static let data_db =  DB.sqlite(db_name: "sysnum.db",bundle:Bundle(for: JoUser.self))
    static func save(msgID:String){
        let sql = "insert into msg(msg_id) values('\(msgID)')"
        data_db.exec(sql: sql)
    }
    

    static func have(msgID:String)->Bool{
        let sql = "select * from msg where msg_id = '\(msgID)'"
        let list = data_db.query(sql: sql)
        var have = false
        if list.count > 0{
            have = true
        }
        return have
    }

    static func check(message:NSMutableDictionary) ->(type:String,link:String,isExist:Bool){

        let msgBbj = message
//        let mType = msgBbj["messageType",""]
//        let link = msgBbj["link",""]

        let mID = msgBbj["_j_msgid",""]

        let isExist = have(msgID: mID)
        save(msgID: mID)

        return (mID,mID,isExist)
    }




    static func openMessage(message:NSMutableDictionary)
    {

    }

    static var navigationController:UINavigationController?{
        get{
            if let nav = UIViewController.current as? UINavigationController{
                return nav
            }
            else{
                return UIViewController.current?.navigationController
            }
        }
    }
}


